<?php
declare (strict_types = 1);

namespace app\tools;

use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Exception;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

final class SpreadsheetTool
{
    protected $spreadsheet;
    protected $sheet;

    /**
     * ExcelTool constructor.
     */
    public function __construct()
    {
        $this->spreadsheet = new Spreadsheet();
        $this->sheet = $this->spreadsheet->getActiveSheet();
    }

    /**
     * 常规导出csv操作
     *
     * @param $header
     * @param $fields
     * @param $data
     * @param $fileName
     * @return string
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     */
    public function exportCsv($header, $fields, $data, $fileName)
    {
        $this->setHeader($header);
        foreach ($data as $index => $item) {
            $row = $index + 2;
            $len = count($fields);
            for ($i = 0; $i < $len; $i++) {
                $tempFields = explode('.', $fields[$i]);
                $value = count($tempFields) == 1 ? $item[$tempFields[0]] : $item[$tempFields[0]][$tempFields[1]]; // 暂时兼容两层...
                $this->sheet->getCell(chr(65+$i).$row)->setValueExplicit($value,DataType::TYPE_STRING);
            }
        }
        // $writer = new Xlsx($this->spreadsheet);
        $writer = new Csv($this->spreadsheet);
        // 保存在服务器
        $filename = public_path() . 'export' . DIRECTORY_SEPARATOR . $fileName;
        $writer->save($filename);

        return $filename;
    }

    /**
     * 组装单元格
     *
     * @param $fields
     * @param $item
     * @param $index
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     */
    public function packageSpreadsheet($fields, $item, $index)
    {
        $row = $index + 2;
        $len = count($fields);
        for ($i = 0; $i < $len; $i++) {
            $tempFields = explode('.', $fields[$i]);
            $value = count($tempFields) == 1 ? $item[$tempFields[0]] : $item[$tempFields[0]][$tempFields[1]]; // 暂时兼容两层...
            $this->sheet->getCell(chr(65+$i).$row)->setValueExplicit($value,DataType::TYPE_STRING);
        }
    }

    /**
     * 导出组装后的Excel文件
     *
     * @param $fileName
     * @return string
     * @throws Exception
     */
    public function exportExcelFile($fileName)
    {
        ob_clean();
        header("Content-Type:application/octet-stream");
        header('Content-Disposition:attachment;filename=' . $fileName);
        header("Content-Transfer-Encoding:binary");
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($this->spreadsheet);
        $writer->save('php://output');
        exit;
    }

    /**
     * 设置表头
     *
     * @param $header
     * @return $this
     */
    public function setHeader($header)
    {
        $len = count($header);
        $styleArray = [
            'fill' => [
                'fillType' => Fill::FILL_GRADIENT_LINEAR,
                'rotation' => 90, // 旋转角度
                'startColor' => [
                    'argb' => '0070C0',
                ],
                'endColor' => [
                    'argb' => '0070C0',
                ],
            ],
        ];

        for ($i = 0; $i < $len; $i++) {
            $cell = chr(65 + $i) . "1";
            $this->sheet->getStyle($cell)->applyFromArray($styleArray);
            $this->sheet->setCellValue($cell, $header[$i]);
        }
        return $this;
    }
}
